<!DOCTYPE html>
<html lang="zh-cn">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    
    <title>string.replace() 详解 | liuz2&#39;s Blog</title>
    <meta name="viewport" content="width=device-width,minimum-scale=1">
    <meta name="generator" content="Hugo 0.63.1" />
    
    
      <META NAME="ROBOTS" CONTENT="NOINDEX, NOFOLLOW">
    

    
    
      <link href="/dist/css/app.9576afd3b3c158d98f48ec5df01fec6a.css" rel="stylesheet">
    

    

    
      

    

    

    <meta property="og:title" content="string.replace() 详解" />
<meta property="og:description" content="由浅入深的介绍 string.replace 函数" />
<meta property="og:type" content="article" />
<meta property="og:url" content="https://liuz2.gitee.io/posts/string-replace-explained/" />
<meta property="article:published_time" content="2021-08-30T22:15:39+08:00" />
<meta property="article:modified_time" content="2021-08-30T22:15:39+08:00" />
<meta itemprop="name" content="string.replace() 详解">
<meta itemprop="description" content="由浅入深的介绍 string.replace 函数">
<meta itemprop="datePublished" content="2021-08-30T22:15:39&#43;08:00" />
<meta itemprop="dateModified" content="2021-08-30T22:15:39&#43;08:00" />
<meta itemprop="wordCount" content="204">



<meta itemprop="keywords" content="javascript," /><meta name="twitter:card" content="summary"/>
<meta name="twitter:title" content="string.replace() 详解"/>
<meta name="twitter:description" content="由浅入深的介绍 string.replace 函数"/>

	
  </head>

  <body class="ma0 avenir bg-white">

    
   
  

  <header>
    <div class="bg-black">
      <nav class="pv3 ph3 ph4-ns" role="navigation">
  <div class="flex-l justify-between items-center center">
    <a href="/" class="f3 fw2 hover-white no-underline white-90 dib">
      
        liuz2&#39;s Blog
      
    </a>
    <div class="flex-l items-center">
      

      
        <ul class="pl0 mr3">
          
          <li class="list f5 f4-ns fw4 dib pr3">
            <a class="hover-white no-underline white-90" href="/about/" title="About page">
              About
            </a>
          </li>
          
          <li class="list f5 f4-ns fw4 dib pr3">
            <a class="hover-white no-underline white-90" href="/links/" title="Links page">
              Links
            </a>
          </li>
          
          <li class="list f5 f4-ns fw4 dib pr3">
            <a class="hover-white no-underline white-90" href="/timeline/" title="Timeline page">
              Timeline
            </a>
          </li>
          
        </ul>
      
      















    </div>
  </div>
</nav>

    </div>
  </header>



    <main class="pb7" role="main">
      
  
  <article class="flex-l flex-wrap justify-between mw8 center ph3">
    <header class="mt4 w-100">
      <h1 class="f3 athelas mt3 mb1">string.replace() 详解</h1>
      
      
      <time class="f6 mv1 dib tracked" datetime="2021-08-30T22:15:39&#43;08:00">August 30, 2021</time>

      
      
    </header>
    <div class="nested-copy-line-height lh-copy sans-serif f5 nested-links nested-img mid-gray pr4-l w-two-thirds-l"><p><code>string.replace()</code> 用来替换字符串，默认只替换第一个匹配项。它返回新字符串，不改变原始字符串。</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-js" data-lang="js"><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">str</span> <span style="color:#f92672">=</span> <span style="color:#e6db74">&#39;hello world goodbye world&#39;</span>;
<span style="color:#a6e22e">str</span>.<span style="color:#a6e22e">replace</span>(<span style="color:#e6db74">&#39;world&#39;</span>, <span style="color:#e6db74">&#39;tony&#39;</span>);
<span style="color:#75715e">// =&gt; &#39;hello tony goodbye world&#39;
</span></code></pre></div><p>第一个参数可以是正则表达式：</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-js" data-lang="js"><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">str</span> <span style="color:#f92672">=</span> <span style="color:#e6db74">&#39;hello world goodbye world&#39;</span>;
<span style="color:#a6e22e">str</span>.<span style="color:#a6e22e">replace</span>(<span style="color:#e6db74">/world/</span>, <span style="color:#e6db74">&#39;tony&#39;</span>);
<span style="color:#75715e">// =&gt; &#39;hello tony goodbye world&#39;
</span></code></pre></div><p>如果要替换所有的匹配项，需要使用正则表达式的 <code>g</code> 标识位：</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-js" data-lang="js"><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">str</span> <span style="color:#f92672">=</span> <span style="color:#e6db74">&#39;hello world goodbye world&#39;</span>;
<span style="color:#a6e22e">str</span>.<span style="color:#a6e22e">replace</span>(<span style="color:#e6db74">/world/g</span>, <span style="color:#e6db74">&#39;tony&#39;</span>);
<span style="color:#75715e">// =&gt; &#39;hello tony goodbye tony&#39;
</span></code></pre></div><p>第二个参数可以是函数，这个函数常配合正则表达式的捕获组使用。该函数的第 1 个参数表示匹配的整体字符串，后面的参数依次是第 1 个捕获组、第 2 个捕获组&hellip;</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-js" data-lang="js"><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">regexp</span> <span style="color:#f92672">=</span> <span style="color:#e6db74">/:(\w+)/g</span>;
<span style="color:#66d9ef">const</span> <span style="color:#a6e22e">format</span> <span style="color:#f92672">=</span> <span style="color:#e6db74">&#39;:method :url&#39;</span>;
<span style="color:#a6e22e">format</span>.<span style="color:#a6e22e">replace</span>(<span style="color:#a6e22e">regexp</span>, (<span style="color:#a6e22e">match</span>, <span style="color:#a6e22e">property</span>) =&gt; {
    <span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#e6db74">`</span><span style="color:#e6db74">match </span><span style="color:#e6db74">${</span><span style="color:#a6e22e">match</span><span style="color:#e6db74">}</span><span style="color:#e6db74">, property </span><span style="color:#e6db74">${</span><span style="color:#a6e22e">property</span><span style="color:#e6db74">}</span><span style="color:#e6db74">`</span>);
});

<span style="color:#75715e">// =&gt; match :method, property method
</span><span style="color:#75715e"></span><span style="color:#75715e">// =&gt; match :url, property url
</span></code></pre></div><p>可以使用它替换动态参数：</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-js" data-lang="js"><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">regexp</span> <span style="color:#f92672">=</span> <span style="color:#e6db74">/:(\w+)/g</span>;
<span style="color:#66d9ef">const</span> <span style="color:#a6e22e">format</span> <span style="color:#f92672">=</span> <span style="color:#e6db74">&#39;:method :url&#39;</span>;
<span style="color:#66d9ef">const</span> <span style="color:#a6e22e">req</span> <span style="color:#f92672">=</span> {
    <span style="color:#a6e22e">method</span><span style="color:#f92672">:</span> <span style="color:#e6db74">&#39;GET&#39;</span>,
    <span style="color:#a6e22e">url</span><span style="color:#f92672">:</span> <span style="color:#e6db74">&#39;http://example.com&#39;</span>,
};
<span style="color:#66d9ef">const</span> <span style="color:#a6e22e">result</span> <span style="color:#f92672">=</span> <span style="color:#a6e22e">format</span>.<span style="color:#a6e22e">replace</span>(<span style="color:#a6e22e">regexp</span>, (<span style="color:#a6e22e">match</span>, <span style="color:#a6e22e">property</span>) =&gt; {
    <span style="color:#66d9ef">return</span> <span style="color:#a6e22e">req</span>[<span style="color:#a6e22e">property</span>];
});
<span style="color:#a6e22e">console</span>.<span style="color:#a6e22e">log</span>(<span style="color:#a6e22e">result</span>);
<span style="color:#75715e">// =&gt; GET http://example.com
</span></code></pre></div><p>可以用它转换字符串风格，比如从 <code>foo-bar</code> 到 <code>fooBar</code>：</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-js" data-lang="js"><span style="color:#66d9ef">const</span> <span style="color:#a6e22e">camelizeRE</span> <span style="color:#f92672">=</span> <span style="color:#e6db74">/-(\w)/g</span>;
<span style="color:#66d9ef">function</span> <span style="color:#a6e22e">camelize</span>(<span style="color:#a6e22e">str</span>) {
    <span style="color:#66d9ef">return</span> <span style="color:#a6e22e">str</span>.<span style="color:#a6e22e">replace</span>(<span style="color:#a6e22e">camelizeRE</span>, <span style="color:#66d9ef">function</span> (<span style="color:#a6e22e">_</span>, <span style="color:#a6e22e">c</span>) {
        <span style="color:#66d9ef">if</span> (<span style="color:#a6e22e">c</span>) <span style="color:#66d9ef">return</span> <span style="color:#a6e22e">c</span>.<span style="color:#a6e22e">toUpperCase</span>();
        <span style="color:#66d9ef">return</span> <span style="color:#e6db74">&#39;&#39;</span>;
    });
}

<span style="color:#a6e22e">camelize</span>(<span style="color:#e6db74">&#39;foo-bar&#39;</span>);
<span style="color:#75715e">// =&gt; fooBar
</span></code></pre></div><p>第二个参数还可以使用一些固定的模板字符串，比如 <code>$$</code>, <code>$&amp;</code> 等。这些模板字符串的含义如下：</p>
<table>
<thead>
<tr>
<th>模板字符串</th>
<th>插入的值</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>$$</code></td>
<td>插入字符 &ldquo;$&rdquo;</td>
</tr>
<tr>
<td><code>$&amp;</code></td>
<td>插入匹配的子串</td>
</tr>
<tr>
<td><code>$`</code></td>
<td>插入匹配子串左侧的字符串</td>
</tr>
<tr>
<td><code>$'</code></td>
<td>插入匹配子串右侧的字符串</td>
</tr>
<tr>
<td><code>$n</code></td>
<td>n 为小于 100 的正整数，插入第 n 个捕获组内的匹配子串。n 从 1 开始计算</td>
</tr>
<tr>
<td><code>$&lt;Name&gt;</code></td>
<td>Name 是一个捕获组名称。只在支持命名捕获组中有用</td>
</tr>
</tbody>
</table>
<p>比如，给电话号码增加方括号：</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-js" data-lang="js"><span style="color:#e6db74">&#39;my phone is 12345678901&#39;</span>.<span style="color:#a6e22e">replace</span>(<span style="color:#e6db74">/\d{11}/</span>, <span style="color:#e6db74">&#39;[$&amp;]&#39;</span>);
<span style="color:#75715e">// =&gt; &#39;my phone is [12345678901]&#39;
</span></code></pre></div><p>比如，屏蔽电话号码中间的四位数字：</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-js" data-lang="js"><span style="color:#e6db74">&#39;12345678901&#39;</span>.<span style="color:#a6e22e">replace</span>(<span style="color:#e6db74">/(\d{3})\d{4}(\d{4})/</span>, <span style="color:#e6db74">&#39;$1****$2&#39;</span>);
<span style="color:#75715e">// =&gt; &#39;123****8901&#39;
</span></code></pre></div><h2 id="ref">REF</h2>
<ol>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace">String.prototype.replace()</a>, MDN</li>
<li><a href="https://github.com/vuejs/vue/blob/7094fc081ade9208e9f759a9145ec34a28143bf1/src/shared/util.js#L164-L167">camelize()</a>, vue/src/shared/utils.js</li>
</ol>
<a href="https://gitee.com/liuz2/liuz2/blob/master/content/posts/string-replace-explained.md#tree_comm_title" class="no-underline db b--black pa2 tc bg-black-90" style="color:#eee;">进入留言</a><ul class="pa0">
  
   <li class="list dib">
     <a href="/tags/javascript" class="link f5 grow no-underline br-pill ba ph3 pv2 mb2 dib black sans-serif">javascript</a>
   </li>
  
</ul>
<div class="mt6 instapaper_ignoref">
      
      
      </div>
    </div>

    <aside class="w-30-l mt6-l">




  <div class="bg-light-gray pa3 nested-list-reset nested-copy-line-height nested-links">
    <p class="f5 b mb3">相关內容</p>
    <ul class="pa0 list">
	   
	     <li  class="mb2">
          <a href="/posts/change-event-of-input/">关于文本输入框 change 事件触发时机</a>
        </li>
	    
    </ul>
</div>

</aside>

  </article>

    </main>
    <footer class="bg-black bottom-0 w-100 pa3" role="contentinfo">
  <div class="flex justify-between">
  <a class="f4 fw4 hover-white no-underline white-70 dn dib-ns pv2 ph3" href="https://liuz2.gitee.io/" >
    &copy;  liuz2's Blog 2022 
  </a>
    <div>














</div>
  </div>
</footer>

    

  <script src="/dist/js/app.3fc0f988d21662902933.js"></script>


  </body>
</html>
